<template>
    <div class="goodsSku">
        <van-sku
                v-model="show"
                :sku="sku"
                :goods="goods"
                :goods-id="goodsId"
                @buy-clicked="onBuyClicked"
                @add-cart="onAddCartClicked">
<!--            <template slot="sku-actions" >-->
<!--                <div class="btnWrap text-white-pk">-->
<!--                    <div class="footerBtn bg-yellow">加入购物车</div>-->
<!--                    <div class="footerBtn bg-red-pk">立即购买</div>-->
<!--                </div>-->
<!--            </template>-->
        </van-sku>
    </div>
</template>

<script>
    export default {
        name: "goodsSku",
        props: {
            goodsInfo: {
                type: Object,
                default: function () {
                    return {}
                }
            }
        },
        components: {},

        data() {
            return {
                show: false,
                sku: {
                    // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
                    // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
                    tree: [],
                    list: [],
                    // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
                    price: "", // 默认价格（单位元）
                    stock_num: 1, // 商品总库存
                    collection_id: 0, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
                    none_sku: false, // 是否无规格商品
                    hide_stock: false // 是否隐藏剩余库存
                },
                goods: {
                    // 商品标题
                    title: '',
                    // 默认商品 sku 缩略图
                    picture: '#'
                },
                attrValList: [],
                attrList: [],
                attrTreeList: [],
                standardListOrigin: [],//规格模板
                // standardList: [],
                standardListFmt: [],
                goodsAttrList: []
            }
        },
        mounted() {
            if(this.typeId) {
                this.initData()
            }
        },
        computed: {
            goodsId() {
                return this.goodsInfo.goodsId
            },
            typeId() {
                return this.goodsInfo.typeId
            }
        },
        watch: {
            typeId(val) {
                if(val) {
                    this.initData()
                }
            }
        },
        methods: {
            initData() {
                this.getGoodsStandard();
                this.goodsAttrList = this.goodsInfo.goodsAttrList;
                this.goods.title = this.goodsInfo.goodsName;
                this.goods.picture = this.goodsInfo.goodsThumb;
                this.sku.price = this.goodsInfo.originalPrice;
            },
            handleAttrPop() {
                this.show = true
            },
            getGoodsStandard() {
                this.$api.getGoodsStandard(this.typeId).then( res => {
                    let result = this.$resData(res);
                    if(result) {
                        this.standardListOrigin = result;
                        this.buildTree()
                    }
                })
            },
            //按有赞模板处理数据
            buildTree() {
                this.attrDedupe();
                this.standardUseFmt();
                this.stdContentUse();
                this.treeFmt()
            },
            //获取goodsInfo 中已选的规格
            attrDedupe() {
                let tempColumn = [];//table表格列
                this.goodsInfo.goodsAttrList.map(item => {
                    let attrData = JSON.parse(item.attrData);
                    attrData.id = item.attrId;
                    attrData.price = item.goodsPrice*100;
                    attrData.stock_num = item.store;
                    this.attrList.push(attrData);
                    tempColumn = tempColumn.concat(Object.keys(attrData));
                });
                this.attrValList = Array.from(new Set(tempColumn));
            },
            //规格模板中未只用到的规格删除
            standardUseFmt() {
                let tempStandardList = [];
                for(let i=0; i<this.standardListOrigin.length; i++) {
                    let item = this.standardListOrigin[i];
                    if(this.attrValList.includes(item.stdName)) {
                        let stdContent = item.stdContent;
                        let stdArr = stdContent.split('\n').filter( ele => {
                            return (ele !== "" && ele !== undefined && ele != null)
                        });
                        tempStandardList.push({
                            stdName: item.stdName,
                            stdArr: stdArr,
                            iconStatus: item.iconStatus
                        })
                    }
                }
                this.standardListFmt = tempStandardList
            },
            //规格项中的内容，删除未使用到的
            stdContentUse() {
                let tempObj = {};
                this.attrValList.forEach(item => {
                    tempObj[item] = [];
                    this.attrList.forEach(attrItem => {
                        if(!tempObj[item].includes(attrItem[item])) {
                            tempObj[item].push(attrItem[item])
                        }
                    })
                });
                this.standardListFmt.forEach(item => {
                    let searchArr = tempObj[item.stdName];
                    let tempArr = [];
                    //let stdListTemp = [];
                    // 判断规格是否可以上传图片； 遍历规格项，寻找是否上传图片
                    // 只有一栏可上传图片（后台限定）
                    for(let i=0; i<item.stdArr.length; i++) {
                        if(searchArr.includes(item.stdArr[i])){
                            let picture = "";
                            //debugger;
                            if(item.iconStatus == "1") {
                                picture = this.stdImgMatch(item.stdName, item.stdArr[i])
                            }
                            tempArr.push({
                                id: item.stdArr[i],
                                name: item.stdArr[i],
                                imgUrl: picture,
                                previewImgUrl: picture
                            });
                            //stdListTemp.push(item.stdArr[i])
                        }
                    }
                    item.stdArr = tempArr;
                    // this.standardList.push({
                    //     stdName: item.stdName,
                    //     stdArr: stdListTemp,
                    // })
                })
            },
            treeFmt() {
                let tempTree = [];
                this.standardListFmt.forEach(item => {
                    tempTree.push({
                        k: item.stdName,
                        v: item.stdArr,
                        k_s: item.stdName
                    });
                });
                this.sku.tree = tempTree;
                this.sku.list = this.attrList;
            },
            //购买
            onBuyClicked(val) {
                //console.log(val);
                val.selectedSkuComb.picture = this.attrSelectPicture(val.selectedSkuComb.id);
                this.$emit("orderConfirm", val)
                //this.$router.push({name: "orderConfirm" ,params: val })
            },
            //加入购物车
            onAddCartClicked() {
                //console.log(val)
            },
            //查找规格图片
            stdImgMatch(attrName, stdName) {
                let pictureUrl = "";
                for( let i=0; i<this.goodsAttrList.length; i++) {
                    let item = this.goodsAttrList[i];
                    if(item.picture) {
                        let attrData = JSON.parse(item.attrData);
                        if(attrData[attrName] == stdName) {
                            pictureUrl = item.picture;
                            break
                        }
                    }
                }
                return pictureUrl
            },
            // 选择规格后，规格attrId 获取相应的图片
            attrSelectPicture(id) {
                let picture = this.picture;
                for( let i=0; i<this.goodsAttrList.length; i++) {
                    let item = this.goodsAttrList[i];
                    if(item.attrId == id) {
                        picture = item.picture;
                        break
                    }
                }
                return picture
            }
        }
    }
</script>

<style lang="scss" scoped>
    .goodsSku{
        .btnWrap {
            padding: 10px 10px 15px;
            display: flex;
            justify-content: space-between;
            .footerBtn {
                height: 35px;
                line-height: 35px;
                text-align: center;
                width: 150px;
                border-radius: 4px;
            }
        }
    }
</style>
